""" 原理代码
from config import DISPLAY_IMAGE
from visual_image import modern_plot_visualization_data


def get_translation_field(sorted_data_overlap):
    sorted_translation_data = sorted_data_overlap

    for cluster_data in sorted_data_overlap:
        for content_idx in range(0, len(cluster_data), 2):
            cur_content_line = cluster_data[content_idx]
            translation_line = cluster_data[content_idx + 1]
            # 将对应的翻译插入对应的正文部分
            for idx in range(1,len(cur_content_line)):


                cur_content_elem = cur_content_line[idx]
                cur_content_elem_x_start = cur_content_elem['x_start']
                # 如果是正文最后一个元素，则将从cur_content_elem_x_start到translation_elem[translation_line[len(translation_line)-1]]['x_end']
                # 通俗来讲，就是把从正文最后一个元素开始，把翻译剩余的元素全部给它
                if idx == len(cur_content_line)-1:

                    continue
                prev_content_elem = cur_content_line[idx-1]
                prev_content_elem_x_start = prev_content_elem['x_start']


                # 将cur_content_elem_x_start-prev_content_elem_x_start(不等于)范围内的translation_line的translation_elem插入到content_elem字段内
                translation_info = cur_content_elem['translation_info']

                # 这是完整的翻译--> 取对应的translation_elem['word']-->literal_translation+=translation_elem['word']
                literal_translation = translation_info['literal_translation']
                # 这是要放translation_elem信息
                translation_elem = translation_info['translation_elem']


    if DISPLAY_IMAGE:
        modern_plot_visualization_data(sorted_translation_data)

    pass
"""


def get_translation_field(sorted_data_overlap):
    """
    为每个正文字符匹配对应的翻译字符，只返回正文内容

    Args:
        sorted_data_overlap: 重叠排序后的数据，格式为 [[栏1行1, 栏1行2, 栏1行3...], [栏2行1, 栏2行2...]]
    Returns:
        list: 只包含正文内容（附带翻译信息）的数据
    """
    sorted_translation_data = []
    constant_c = 5  # 边界调整常数
    for column_idx, column_data in enumerate(sorted_data_overlap):
        # print(f"处理第 {column_idx + 1} 栏的翻译匹配")
        translated_column = []

        # 遍历每对正文-翻译行
        for content_idx in range(0, len(column_data) - 1, 2):
            content_line = column_data[content_idx]  # 正文行
            translation_line = column_data[content_idx + 1]  # 翻译行

            if not content_line or not translation_line:
                continue

            # print(f"  正文行{content_idx // 2 + 1}: {len(content_line)}字, 翻译行: {len(translation_line)}字")

            # 确保按x坐标排序
            content_line.sort(key=lambda x: x['x_start'])
            translation_line.sort(key=lambda x: x['x_start'])

            # 获取翻译行的边界信息
            translation_max_x = translation_line[-1]['x_end'] if translation_line else 0
            translation_min_x = translation_line[0]['x_start'] if translation_line else 0

            # 为每个正文字符匹配翻译
            translated_content_line = []
            for idx in range(len(content_line)):
                content_elem = content_line[idx].copy()  # 创建副本

                # 确定翻译范围
                if idx < len(content_line) - 1:
                    # 普通字符：当前x_start到下一个字符x_start - c
                    x_start_bound = max(content_elem['x_start'], translation_min_x)
                    x_end_bound = min(content_line[idx + 1]['x_start'] - constant_c, translation_max_x)
                else:
                    # 最后一个字符：当前x_start到翻译行结束
                    x_start_bound = max(content_elem['x_start'], translation_min_x)
                    x_end_bound = translation_max_x
                    # print(f"    最后一个字符 '{content_elem['word']}' 范围: {x_start_bound:.1f}-{x_end_bound:.1f}")

                # 查找在这个范围内的翻译字符
                matched_translations = []
                for trans_elem in translation_line:
                    trans_center = (trans_elem['x_start'] + trans_elem['x_end']) / 2
                    if x_start_bound <= trans_center <= x_end_bound:
                        matched_translations.append(trans_elem)

                # 按x坐标排序并构建翻译文本
                matched_translations.sort(key=lambda x: x['x_start'])
                literal_translation = ''.join([t['word'] for t in matched_translations])

                # 添加翻译信息到正文字符
                content_elem['translation_info'] = {
                    'literal_translation': literal_translation,
                    # 'translation_elems': matched_translations,
                    # 'match_count': len(matched_translations)
                }

                translated_content_line.append(content_elem)
                # print(f"    '{content_elem['word']}' → '{literal_translation}'")

            # 只添加正文行（不添加翻译行）
            translated_column.append(translated_content_line)

        sorted_translation_data.append(translated_column)

    return sorted_translation_data


# 辅助函数：提取纯文本结果
def extract_final_text(sorted_translation_data):
    """
    从处理结果中提取最终的文本内容

    Returns:
        tuple: (中文文本, 翻译文本)
    """
    chinese_text = []
    translation_text = []

    for column_idx, column_data in enumerate(sorted_translation_data):
        chinese_text.append(f"\n=== 第 {column_idx + 1} 栏 ===")
        translation_text.append(f"\n=== Column {column_idx + 1} ===")

        for line_idx, line_data in enumerate(column_data):
            chinese_line = ''.join([elem['word'] for elem in line_data])
            translation_line = ' '.join([elem['translation_info']['literal_translation'] for elem in line_data])

            chinese_text.append(chinese_line)
            translation_text.append(translation_line)

    return '\n'.join(chinese_text), '\n'.join(translation_text)
